package il.ac.biu.cs.grossmm.xmlUtil;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class XmlException extends Exception {
	
	private static final long serialVersionUID = 8070793146379481135L;
	
	final Node node;
	
	public XmlException(Node node) {	
		this.node = null;
	}
	
	public XmlException(Node node, String reason) {
		super(reason);
		this.node = node;
	}
	
	public XmlException(Node node, Exception exception) {
		super(exception);
		this.node = node;
	}
	
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer(super.toString());
		
		for( Node node = this.node; node != null; node = node.getParentNode()) {
			sb.append(" at ").append(node.getNodeName()+atts(node));
		}
		
		return sb.toString();
	}

	private String atts(Node node) {
		if( node.getNodeType() != Node.ELEMENT_NODE )
			return "";
		
		NamedNodeMap atts = node.getAttributes();
		
		int len = atts.getLength(); 
		if( len == 0 )
			return "";
			
		StringBuffer sb = new StringBuffer("[");
		
		for( int i=0; i<len; i++) {
			Node n = atts.item(i);
			if( i>0 )
				sb.append(' ');
			sb.append(n.getNodeName()).append("='").append(n.getNodeValue()).append("'");
		}
		
		sb.append(']');
		
		return sb.toString();
	}
	
}
